package com.zhxh.nzpos.goods;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.Toast;

import com.petpet.sc.widget.SegmentedControl;
import com.zhxh.nzpos.BaseActivity;
import com.zhxh.nzpos.R;
import com.zhxh.nzpos.dao.CategoryDao;
import com.zhxh.nzpos.dao.GoodsDao;
import com.zhxh.nzpos.model.Category;
import com.zhxh.nzpos.model.Goods;

/**
 * 商品管理
 * 
 * @author wangzt
 * 
 */
public class GoodsManageActivity extends BaseActivity implements
		GoodsItemCallBack {

	private ArrayList<GoodsItem> goodsItems;
	private GoodsListAdapter listAdapter;
	private GoodsDao goodsDao;
	private CategoryDao categoryDao;

	protected View footerView;
	protected static final int PAGESIZE = 15;
	protected static int TOTAL_SIZE;
	protected boolean loading = false;
	private Category cate;
	private EditText dealOcr;
	private ListView listView;
	private SegmentedControl tabs;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_goods_manage);
		goodsDao = new GoodsDao(this);
		categoryDao = new CategoryDao(getApplicationContext());
		initViews();
	}

	private void initViews() {
		listView = (ListView) findViewById(R.id.goods_listview);

		footerView = ((LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
				R.layout.footer, null, false);
		// goodsItems = new ArrayList<GoodsItem>();
		initTab();
		initData();
		// TODO 扫描条码添加一项
		dealOcr = (EditText) findViewById(R.id.goods_ocr_et);
		ImageView addBtn = (ImageView) findViewById(R.id.goods_add_btn);
		addBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO 需要从数据库中根据编号查找
				Intent intent = new Intent();

				Bundle b = new Bundle();
				if (cate == null) {
					Toast.makeText(GoodsManageActivity.this, "请先创建商品分类",
							Toast.LENGTH_SHORT).show();
					return;
				}
				b.putSerializable("cate", cate);
				intent.putExtras(b);
				intent.setClass(getApplicationContext(), GoodsAddActivity.class);
				// startActivity(intent);
				startActivityForResult(intent, 0);
			}
		});

		listAdapter = new GoodsListAdapter(getLayoutInflater(), goodsItems,
				this);
		listView.setAdapter(listAdapter);
		listView.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView arg0, int scrollState) {
				// nothing here
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				boolean loadmore = load(firstVisibleItem, visibleItemCount,
						totalItemCount);
				//System.out.println("###############loadmore===" + loadmore);
				if (loadmore) {
				//	System.out.println("###############===" + footerView);
					loading = true;

					(new LoadNextPage()).execute("");
				}
			}
		});
		/*
		 * ImageView cancelBtn = (ImageView)
		 * findViewById(R.id.goods_cancel_btn); cancelBtn.setOnClickListener(new
		 * OnClickListener() { public void onClick(View v) { finish(); } });
		 */

	}

	/*
	 * @Override public void onStart() { super.onStart(); //
	 * (Button)findViewByTag(cate.getId()); if(cate != null) { Button btn =
	 * (Button) tabs.findViewWithTag(cate.getId()); btn.setPressed(true); }
	 * 
	 * // initData(); }
	 */

	@Override
	public void onResume() {
		super.onResume();
		System.out.println("###############loadmore===onResume");
		// (Button)findViewByTag(cate.getId());
		if (cate != null) {
			System.out.println("###############loadmore===on22Resume");
			Button btn = (Button) tabs.findViewWithTag(cate.getId());
			btn.setPressed(true);
		}

		// initData();
	}

	private void initTab() {

		/*
		 * RelativeLayout tabs = (RelativeLayout) findViewById(R.id.cate);
		 * 
		 * List<Category> categorys = categoryDao.getAllParents();
		 * System.out.println("size="+categorys.size()); for(int i = 0 ; i <
		 * categorys.size(); i++) { Category category = categorys.get(i);
		 * 
		 * Button btn = new Button(this); btn.setTag(category.getId());
		 * btn.setId(i); btn.setText(category.getCategory()); // LayoutParameter
		 * //tabs. LayoutParams params = new
		 * LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
		 * if(i == 0 ) { btn.setBackgroundResource(R.drawable.btn_head);
		 * btn.setPressed(true); } else if(i == categorys.size() -1){
		 * btn.setBackgroundResource(R.drawable.btn_tail); params.leftMargin =
		 * -12; params.addRule(RelativeLayout.RIGHT_OF,i-1); } else {
		 * params.addRule(RelativeLayout.RIGHT_OF,i-1);
		 * btn.setBackgroundResource(R.drawable.btn_midle); params.leftMargin =
		 * -12; } // params.addRule(verb) tabs.addView(btn,params); }
		 */
		tabs = (SegmentedControl) findViewById(R.id.cate);

		List<Category> categorys = categoryDao.getAllParents();
		System.out.println("size=" + categorys.size());
		for (int i = 0; i < categorys.size(); i++) {
			Category category = categorys.get(i);

			Button btn = new Button(this);
			btn.setTag(category.getId());
			btn.setId(i);
			btn.setOnClickListener(tabListener);
			btn.setText(category.getCategory());
			btn.setTextSize(20);
			// LayoutParameter
			// tabs.
			LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
			if (i == 0) {
				cate = category;
				btn.setBackgroundResource(R.drawable.btn_head);
				btn.setPressed(true);

			} else if (i == categorys.size() - 1) {
				btn.setBackgroundResource(R.drawable.btn_tail);
				params.leftMargin = -16;
				// params.addRule(RelativeLayout.RIGHT_OF,i-1);
			} else {
				// params.addRule(RelativeLayout.RIGHT_OF,i-1);
				btn.setBackgroundResource(R.drawable.btn_midle);
				params.leftMargin = -16;
			}
			// params.addRule(verb)
			tabs.addView(btn, params);
		}

	}

	private void initData() {
		initCountSize();
		// listView.addFooterView(footerView, null, false);
		View newview = new View(this);
		listView.addHeaderView(newview);
		goodsItems = new ArrayList<GoodsItem>();
		// DBHelper dbHelper = new DBHelper(getApplicationContext());
		// dbHelper.openDatabase();
		if (cate != null) {
			ArrayList<Goods> goods = (ArrayList) goodsDao.getScrollData(
					cate.getId(), 0, PAGESIZE);
			for (Goods goodsz : goods) {
				GoodsItem item = copyProperties(goodsz);
				goodsItems.add(item);
			}
		}
		// listView.removeFooterView(footerView);

	}

	private void initCountSize() {
		if (cate != null)
			TOTAL_SIZE = goodsDao.getCount(cate.getId());
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		switch (resultCode) {
		case RESULT_OK:
			// tabs.findViewWithTag(tag);
			Bundle b = data.getExtras();
			String goodsid = data.getStringExtra("goodsid");
			GoodsItem goods = (GoodsItem) b.getSerializable("goods");
			// String string = b.getString("CALCULATION");
			if (goodsid != null && goodsid.length() > 0) {
				for (int i = 0; i < goodsItems.size(); i++) {
					GoodsItem item = goodsItems.get(i);
					if (item.getId().equals(goodsid)) {
						item.setId(goods.getId());
						item.setCategoryId(goods.getCategoryId());
						item.setCategoryName(goods.getCategoryName());
						item.setName(goods.getName());
						item.setNote(goods.getNote());
						item.setPrice1(goods.getPrice1());
						item.setPrice2(goods.getPrice2());
						item.setSpecification(goods.getSpecification());
						item.setUnits1(goods.getUnits1());
						item.setUnits2(goods.getUnits2());
						item.setCode(goods.getCode());

					}
				}
			} else {
				goodsItems.add(0, goods);
			}
			if (listAdapter != null) {
				listAdapter.notifyDataSetChanged();
			}

		}

	}

	public void search(View view) {
		final EditText dealOcr = (EditText) findViewById(R.id.goods_ocr_et);
		Editable ocr = dealOcr.getText();
		if (ocr != null) {
			String ocrStr = ocr.toString();
			if (goodsItems == null) {
				goodsItems = new ArrayList<GoodsItem>();
			} else {
				goodsItems.clear();

			}
			GoodsDao dao = new GoodsDao(this);
			Goods goods = dao.find(ocrStr.trim());
			if (goods != null) {
				GoodsItem item = copyProperties(goods);
				goodsItems.add(item);
				if (listAdapter != null) {
					listAdapter.notifyDataSetChanged();
				}
				TOTAL_SIZE = 1;
			}
		}

	}

	private GoodsItem copyProperties(Goods goods) {
		GoodsItem item = new GoodsItem();
		item.setId(goods.getId());
		item.setCategoryId(goods.getCategoryId());
		item.setCategoryName(goods.getCategoryName());
		item.setName(goods.getName());
		item.setNote(goods.getNote());
		item.setPrice1(goods.getPrice1());
		item.setPrice2(goods.getPrice2());
		item.setSpecification(goods.getSpecification());
		item.setUnits1(goods.getUnits1());
		item.setUnits2(goods.getUnits2());
		item.setCode(goods.getCode());
		item.setPoints(goods.getPonits());
		return item;
	}

	public void list(View view) {

		Toast.makeText(this, "aaaa=" + view.getId(), Toast.LENGTH_SHORT).show();
	}

	OnClickListener tabListener = new OnClickListener() {
		public void onClick(View v) {

			String cateid = (String) v.getTag();
			cate.setCategory(((Button) v).getText().toString());
			cate.setId(cateid);
			if (goodsItems != null) {
				goodsItems.clear();
			} else
				goodsItems = new ArrayList<GoodsItem>();
			initCountSize();
			// DBHelper dbHelper = new DBHelper(getApplicationContext());
			// dbHelper.openDatabase();
			ArrayList<Goods> goods = (ArrayList) goodsDao.getScrollData(cateid,
					0, PAGESIZE);
			for (Goods goodsz : goods) {
				GoodsItem item = copyProperties(goodsz);
				goodsItems.add(item);
				if (listAdapter != null) {
					listAdapter.notifyDataSetChanged();
				}
			}
		}
	};

	protected class LoadNextPage extends
			AsyncTask<String, Void, ArrayList<Goods>> {
		private ArrayList<Goods> newData = null;

		@Override
		protected void onPreExecute() {
			//System.out.println("@@@@!!!!!!!!!!!!!!1111111111==" + footerView);
			listView.addFooterView(footerView, null, false);

	/*		System.out.println("@@@@!!!!!!!!!!!!!!1111111111=="
					+ listView.getFooterViewsCount());*/
			super.onPreExecute();
		}

		@Override
		protected ArrayList<Goods> doInBackground(String... arg0) {
			// para que de tiempo a ver el footer ;)
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				Log.e("AbstractListActivity", e.getMessage());
			}
			newData = goodsDao.getScrollData(cate.getId(),
					listAdapter.getCount(), PAGESIZE);
			Log.i("LoadNextPage= doInBackground===", "" + newData.size());
			return null;
		}

		@Override
		protected void onPostExecute(ArrayList<Goods> result) {
			// CustomListAdapter customArrayAdapter = ((CustomListAdapter)
			// getListAdapter());
			for (Goods value : newData) {
				Log.i("LoadNextPage== customArrayAdapter  add ==",
						value.getName());

				GoodsItem item = copyProperties(value);
				listAdapter.getItems().add(item);
			}
			listAdapter.notifyDataSetChanged();
		//	System.out.println("@@@@!!!!!!!!!!!!!!==" + footerView);
			listView.removeFooterView(footerView);
			// listView.removeView(footerView);
			Log.i("LoadNextPage==onPostExecute==", "");
			// getListView().removeFooterView(footerView);
			// updateDisplayingTextView();
			if (newData.size() == 0) {
				Toast.makeText(getApplicationContext(), "没有更多数据",
						Toast.LENGTH_SHORT).show();
			}
			loading = false;
		}

	}

	protected boolean load(int firstVisibleItem, int visibleItemCount,
			int totalItemCount) {
		boolean lastItem = firstVisibleItem + visibleItemCount == totalItemCount
				&& listView.getChildAt(visibleItemCount - 1) != null
				&& listView.getChildAt(visibleItemCount - 1).getBottom() <= listView
						.getHeight();
		boolean moreRows = listAdapter.getCount() < TOTAL_SIZE;
		return moreRows && lastItem && !loading;

	}

	// public abstract CustomListAdapter getListAdapter();

	@Override
	public void onPostResume() {
		super.onPostResume();
		if (cate != null) {
		//	System.out.println("###############loadmore===onPostResume");
			Button btn = (Button) tabs.findViewWithTag(cate.getId());
			btn.setPressed(true);
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		if (cate != null) {
		//	System.out.println("###############loadmore===onPause");
			Button btn = (Button) tabs.findViewWithTag(cate.getId());
			btn.setPressed(true);
		}
	}

	@Override
	public void onDelete(final String id, String name) {

		new AlertDialog.Builder(this)
				.setTitle(R.string.goods_category_delete_dialog_title)
				.setMessage("确定要删除商品 " + name + "?")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

						goodsDao.delete(id);
						// goodsItems.remove(position);
						for (int i = 0; i < goodsItems.size(); i++) {
							GoodsItem item = goodsItems.get(i);
							if (item.getId().equals(id)) {
								goodsItems.remove(i);
								break;
							}
						}
						listAdapter.notifyDataSetChanged();
						// 确定按钮事件
						// setResult(RESULT_OK);
						dialog.dismiss();
						if (cate != null) {
							Button btn = (Button) tabs.findViewWithTag(cate
									.getId());
							btn.setPressed(true);
						}
						// finish();
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						// 取消按钮事件
						dialog.dismiss();
						if (cate != null) {
							Button btn = (Button) tabs.findViewWithTag(cate
									.getId());
							btn.setPressed(true);
						}
					}
				}).show();
	}

	@Override
	public void onUpdate(String id) {
		Intent intent = new Intent();
		intent.putExtra("goodsid", id);
		Bundle b = new Bundle();
		b.putSerializable("cate", cate);
		intent.putExtras(b);
		intent.setClass(getApplicationContext(), GoodsAddActivity.class);
		// startActivity(intent);
		startActivityForResult(intent, 0);
	}

}
